import { defineStore } from 'pinia'
import { sendMessage } from '@/api/chat'

export const useChatStore = defineStore('chat', {
  state: () => ({
    chatHistory: [],
    loading: false,
    currentMessage: null
  }),
  
  actions: {
    async sendMessage(message) {
      try {
        this.loading = true
        
        // 添加用户消息
        const userMessage = {
          role: 'user',
          content: message,
          time: new Date()
        }
        this.chatHistory.push(userMessage)
        
        // 添加 AI 消息占位
        this.currentMessage = {
          role: 'ai_assistant',
          content: '',
          time: new Date(),
          sources: []
        }
        this.chatHistory.push(this.currentMessage)
        
        // 发送请求
        const response = await fetch('/api/chat', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            message: message,
            history: this.chatHistory.slice(0, -2).map(msg => ({
              ...msg,
              content:msg.content
            }))
          })
        })
        
        if (!response.ok) {
          throw new Error('请求失败')
        }
        
        // 处理 SSE 响应
        const reader = response.body.getReader()
        const decoder = new TextDecoder('utf-8')
        
        while (true) {
          const { value, done } = await reader.read()
          if (done) break
          
          const chunk = decoder.decode(value)
          const lines = chunk.split('\n')
          
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              try {
                const data = JSON.parse(line.slice(5))
                
                switch (data.type) {
                  case 'sources':
                    this.currentMessage.sources = data.data.map(source => ({
                      ...source,
                      title: decodeURIComponent(source.title),
                      content: decodeURIComponent(source.content)
                    }))
                    break
                  case 'text':
                    this.currentMessage.content += decodeURIComponent(data.data)
                    break
                  case 'history':
                    // 更新完整历史
                    this.currentMessage = null
                    break
                }
              } catch (e) {
                console.error('解析响应数据失败:', e)
              }
            }
          }
        }
      } catch (error) {
        console.error('发送消息失败:', error)
        throw error
      } finally {
        this.loading = false
        this.currentMessage = null
      }
    },
    
    clearHistory() {
      this.chatHistory = []
      this.currentMessage = null
    }
  },
  
  persist: true
}) 